from django import forms
from django.core.exceptions import ValidationError

from web.forms.bootstrapbase import BootStrapForm
from web import models


class AddWorkOrderModelForm(BootStrapForm, forms.ModelForm):

    class Meta:
        model = models.WorkOrder
        fields = ['order_name', 'order_desc', 'assign_user', 'order_type', 'order_status']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_order_name(self):
        """ 同一个用户在同一个项目下不能创建 两个名称相同的工单 """
        order_name = self.cleaned_data['order_name']
        exists = models.WorkOrder.objects.filter(update_user=self.request.login_user.user, project=self.request.login_user.project, order_name=order_name).exists()
        if exists:
            raise ValidationError('工单已经存在')
        return order_name


